﻿using CommonDevelop;
using CommonDevelop.Scene;
using CommonEngine;
using CommonFP;
using ManageDto;
using ManageService;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebAdmin.Handler;
using WebAdmin.Models;

namespace WebAdmin.Areas.Org.Controllers
{
    /// <summary>
    /// 角色管理
    /// </summary>
    [Area("Org")]
    [Route("Org/[controller]/[action]")]
    public class RoleController : BaseController
    {
        private readonly IRoleService _RoleService;
        private readonly IPermissionManager _Manager;
        /// <summary>
        /// 构造注入
        /// </summary>
        public RoleController(IRoleService RoleService, IPermissionManager manager)
        {
            this._RoleService = RoleService;
            this._Manager = manager;
        }

        /// <summary>
        /// 视图列表
        /// </summary>
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Title = "角色管理";
            return View();
        }

        #region--Select--

        /// <summary>
        /// 视图列表查询（分页）
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string keyword)
        {
            Pagination pag = pagination.ToObject<Pagination>();
            List<RoleDto> data = this._RoleService.GetPageList<RoleDto>(pag, keyword).ToList();
            var jsonData = new
            {
                rows = data,
                total = pag.total,
                page = pag.page,    //由前端配置
                records = pag.records
            };
            return this.SuccessJson(jsonData);
        }

        #endregion

        #region--增删改--

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeAdd()
        {
            RoleDto en = new RoleDto();
            en.RoleCode = this._RoleService.BuildSeq();
            return this.SuccessJson(en);
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeDelete(string keyValue)
        {
            Validation<bool> vb = this._RoleService.Delete(keyValue);
            var ValTuple = vb.Outcome(a => a);
            if (ValTuple.Errors.IsEmpty())
                return ValTuple.result ? this.Success("操作成功") : this.Fail("操作失败");
            else
                return this.Fail(ValTuple.Errors);
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeEdit(string keyValue)
        {
            var outcome = this._RoleService.Get<RoleDto>(keyValue);
            return outcome.Match(() => this.Fail("Null Error"),
                en => this.SuccessJson(en));
        }

        [HttpPost]
        [AjaxOnly]
        [DisableRequestSizeLimit]
        public ActionResult NodeSave([FromForm]string DataText)
        {
            RoleDto em = PageUtility.FormMap<RoleDto>(DataText);
            if (em == null)
                return this.Fail("表单解读失败");
            if (em.FullName.IsEmpty())
                return this.Fail("名称不能为空");
           
            Validation<bool> vb = FP.Error("未执行");
            if (em.ModifyUserId.IsEmpty())
                vb = this._RoleService.Add(em);
            else
                vb = this._RoleService.Save(em);

            var ValTuple = vb.Outcome(a => a);
            if (ValTuple.Errors.IsEmpty())
                return ValTuple.result ? this.Success("操作成功") : this.Fail("操作失败");
            else
                return this.Fail(ValTuple.Errors);
        }

        #endregion

        #region--角色配置数据--

        /// <summary>
        /// 获取树型菜单
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeMenu()
        {
            var Data = BizPage.GetRoleMTree(this._Manager.GetModuleTree());
            return this.ToJsonContent(Data);
        }
        /// <summary>
        /// 获取配置的模块ID
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetRoleModuleID(string id)
        {
            Dictionary<string, bool> Data = this._Manager.GetRoleModuleID(id);
            List<string> Ls = new List<string>();
            foreach (var v in Data)
                if (!v.Value)
                    Ls.Add(v.Key);

            return this.SuccessJson(Ls);
        }
        /// <summary>
        /// 保存导航信息
        /// </summary>
        [HttpPost]
        [AjaxOnly]
        [DisableRequestSizeLimit]
        public ActionResult ConfigSave([FromForm]CollectDto Dto)
        {
            string RoleId = Dto.EnId;
            string Nodes = Dto.ContentTxt;
            //数据还原
            List<jstreeNode> Ls = Nodes.ToList<jstreeNode>();

            //存储NoSql
            List<SimpleItem> data = new List<SimpleItem>();
            foreach (var v in Ls)
                data.Add(new SimpleItem { Key = v.id, Val = v.text, Seq = v.icon == "undetermined" ? 0 : 1 });

            if (this._Manager.SaveModuleTree(RoleId, data))
                return this.Success("保存成功");
            else
                return this.Fail("操作失败");
        }

        #endregion
    }
}